package com.bci.pwtz.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.model.BatchUpdate;
import com.bci.pwtz.service.BatchUpdateService;

@Service
public class BatchUpdateServiceImpl implements BatchUpdateService {

	private static final Logger _logger = Logger.getLogger(BusinessRefServiceImpl.class);
    private JdbcTemplate jdbcTemplate;
    
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public Map<String, List<BatchUpdate>> queryAll() throws PwtzDatabaseException{
		Map<String, List<BatchUpdate>> map = new HashMap<String, List<BatchUpdate>>();
		String sql = "SELECT BATCH_DEVICE_ID FROM T_BATCH_UPDATE GROUP BY BATCH_DEVICE_ID";
		try {
			List<String> deviceIDs = jdbcTemplate.queryForList(sql, String.class);
			for(String deviceID : deviceIDs){
				List<BatchUpdate> result = queryByDeviceID(deviceID);
				map.put(deviceID, result);
			}
		} catch (DataAccessException e) {
			_logger.error("query BatchUpdateServiceImpl.queryAll() fial:", e);
			throw new PwtzDatabaseException();
		}
		return map;
	}
	
	@Override
	public List<BatchUpdate> queryByDeviceID(String deviceID) throws PwtzDatabaseException{
		String sql = "SELECT * FROM T_BATCH_UPDATE WHERE BATCH_DEVICE_ID = ?";
		try {
			return jdbcTemplate.query(sql,new Object[]{deviceID}, new RowMapper<BatchUpdate>(){

				@Override
				public BatchUpdate mapRow(ResultSet rs, int index)
						throws SQLException {
					BatchUpdate bean = new BatchUpdate();
					bean.setBatchid(rs.getInt(1));
					bean.setDeviceid(rs.getInt(2));
					bean.setColumn(rs.getString(3));
					bean.setColumnname(rs.getString(4));
					bean.setSelectcontent(rs.getString(5));
					return bean;
				}
				
			});
		} catch (DataAccessException e) {
			_logger.error("query BatchUpdateServiceImpl.queryByDeviceID("+deviceID+") fial:", e);
			throw new PwtzDatabaseException();
		}
	}

	@Override
	public int bacthUpdate(String[] deviceIDs,Long bacthDeviceID,Map<String,String> columnAndVal) throws PwtzDatabaseException {
		String tableName = BusinessCommonServiceImpl.TABLE_NAME_MAP.get(bacthDeviceID);
		if(tableName==null || deviceIDs==null || deviceIDs.length==0 || columnAndVal==null || columnAndVal.isEmpty()){
			_logger.debug("BatchUpdateServiceImpl.bacthUpdate() param is error: \ndeviceIDs:"+Arrays.toString(deviceIDs)+"\nbacthDeviceID:"+bacthDeviceID+"\ncolumnAndVal:"+columnAndVal);
			return 0;
		}
		
		StringBuffer sql = new StringBuffer("UPDATE "+tableName+" SET ");
		List<String> params = new ArrayList<String>();
		for(Map.Entry<String, String> entry : columnAndVal.entrySet()){
			sql.append(entry.getKey()).append("=").append("?,");
			params.add(entry.getValue());
		}
		sql.deleteCharAt(sql.length()-1);
		sql.append(" where DeviceID in (");
		for(String deviceID : deviceIDs ){
			sql.append("?,");
			params.add(deviceID);
		}
		sql.deleteCharAt(sql.length()-1);
		sql.append(")");
		_logger.debug("execute sql : "+sql.toString());
		_logger.debug("execute sql params : "+Arrays.toString(params.toArray()));
		return jdbcTemplate.update(sql.toString(),params.toArray());
	}

}
